#include <49func.h>
int main(int argc, char *argv[])
{
    // ./3_azhen 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;//服务端地址
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int reuse = 1; // SO_REUSEADDR属性的参数
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
    ERROR_CHECK(ret,-1,"setsockopt"); 
    ret = bind(sockfd, (struct sockaddr *)&addr,sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);

    char buf[4096];
    fd_set rdset;//每次select传入的参数
    fd_set monitorset;//下次select的监听集合
    FD_ZERO(&monitorset);
    FD_SET(sockfd,&monitorset);
    int netfd;
    while(1){
        memcpy(&rdset,&monitorset,sizeof(fd_set));
        select(10,&rdset,NULL,NULL,NULL);//select调用只会修改rdset，不修改monitorset
        if(FD_ISSET(sockfd,&rdset)){
            struct sockaddr_in clientAddr;
            socklen_t clientAddrSize = sizeof(clientAddr);//该变量必须初始化
            //socklen_t clientAddrSize = 0;
            netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&clientAddrSize);
            printf("netfd = %d\n",netfd);
            printf("client ip = %s, port = %d\n", 
                   inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
            //希望服务端在连上一个客户端之后
            //可以和这个客户端聊天
            //不与其他客户端建立连接
            FD_CLR(sockfd,&monitorset);
            FD_SET(STDIN_FILENO,&monitorset);
            FD_SET(netfd,&monitorset);
        }
        if(FD_ISSET(STDIN_FILENO,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                send(netfd,"nishigehaoren",13,0);
                FD_SET(sockfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_CLR(netfd,&monitorset);
                close(netfd);
                printf("woyoudanshenle\n");
                continue;
            }
            send(netfd,buf,sret,0);
        }
        if(FD_ISSET(netfd,&rdset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){//对方断开连接
                FD_SET(sockfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_CLR(netfd,&monitorset);
                close(netfd);
                printf("wohuihaohaode\n");
                continue;
            }
            printf("buf = %s\n", buf);
        }
    }
    return 0;
}

